<?php
/**
 * @author Akulov Denis
 * @since 20.07.2011
 */
class MVC_ModelLoader implements MVC_ModelLoader_Interface {

    private $_arContainerModels = array();


    private $_objContainer = null;


    public function __construct(Container_Interface $objContainer) {
        $this->_objContainer = $objContainer;
    }


    /**
     * @return Config_Interface
     */
    private function getConfig () {
        return $this->getContainer()->get('Config');
    }


    /**
     * @return Container_Interface
     */
    private function getContainer () {
        return $this->_objContainer;
    }


    public function getModel($strModelName) {
        if (!empty($this->_arContainerModels[$strModelName])) {
            return $this->_arContainerModels[$strModelName];
        }

        $strModelPrefix = $this->getConfig()->getAttribute('PREFIX', 'MODEL');
        $strPath = $this->getConfig()->getAttribute('FW_PATHS', 'PROTOTYPE');
        $strPath .= 'MVC/'.str_replace('_', '', $strModelPrefix).'/';
        $strPath .= str_replace('_', '/', $strModelName).'.php';

        if (!is_file($strPath)) {
            throw new Exception('Model file not found :'.$strPath.'}');
        }

        require $strPath;

        $this->_arContainerModels[$strModelName] = $this->newModel($strModelName);

        return $this->_arContainerModels[$strModelName];
    }


    private function newModel ($strModelName) {
        $strModelPrefix = $this->getConfig()->getAttribute('PREFIX', 'MODEL');
        $strModelName = $strModelPrefix.$strModelName;
        return new $strModelName($this->getContainer());
    }
}